<template>
  <div class="main_spac1 maincl">
    <div class="main_white padding10 paddingBottom20">
      <div class="mainor_form">
        <div class="mainor_te">
          <el-button @click="generateClick" class="mainor_tea">生成采购单</el-button>
          <el-button @click="exportb">导出明细</el-button>
          <el-button @click="exportb">导出汇总</el-button>
        </div>
        <el-form
          :inline="true"
          :model="form"
          class="demo-form-inline"
          ref="userListFrom"
          label-width="70px"
        >
          <el-form-item label="配送日期" prop="send_time">
            <el-date-picker
              v-model="form.send_time"
              type="date"
              class="wid220"
              :editable="false"
              placeholder="选择配送日期"
              value-format="yyyy-MM-dd"
              :clearable="false"
            />
          </el-form-item>
          <el-form-item label="商品分类" prop="category_id" class="wid220">
            <el-cascader
              v-model="form.category_id"
              :options="options"
              :props="defaultProps"
            ></el-cascader>
          </el-form-item>
          <div class="more el-form-item" @click="more">
            <span>更多</span>
            <i :class="[{ on: moredata }, ' el-icon-arrow-down']"></i>
          </div>
          <div class="clearfix"></div>
          <el-collapse-transition>
            <div v-if="moredata">
              <el-form-item label="商品名称" prop="name">
                <el-input
                  v-model.trim="form.name"
                  placeholder="商品名称"
                  clearable
                  class="wid220"
                ></el-input>
              </el-form-item>
              <el-form-item label="配送时间" prop="send_time_id">
                <el-select
                  v-model.trim="form.send_time_id"
                  placeholder="配送时间"
                  class="wid220"
                >
                  <el-option label="所有" value=""></el-option>
                  <el-option
                    v-for="(send_time_list, index) in list.send_time_list"
                    :key="index"
                    :label="send_time_list"
                    :value="parseInt(index)"
                  ></el-option>
                </el-select>
              </el-form-item>
            </div>
          </el-collapse-transition>
          <div class="clearfix"></div>
          <el-form-item class="marginTop10">
            <el-button
              class="reset marginLeft10"
              type="primary"
              @click="$refs['userListFrom'].resetFields()"
              >重置</el-button
            >
            <el-button
              type="primary"
              @click="getArticleList"
              :loading="listLoading"
              >搜索</el-button
            >
          </el-form-item>
        </el-form>
      </div>
      <div class="main_num boxdq">
        <div class="main_num_l box">
          <p>
            <em
              >1.商品生成了采购单后不会再出现在列表；2.库存充足的商品自动完成；3.配送中订单（含已完成）预定量、使用库存、在途库存等不会再汇总计算</em
            >
          </p>
        </div>
        <div class="mainsu_te" style="position: relative">
            <el-checkbox v-model="low_stocks" @change="(val)=>{checkboxChange(val,'low_stocks')}">库存不足</el-checkbox>
            <el-tooltip class="item" effect="dark" placement="top">
              <div slot="content">注释：勾选后，仅展示库存不足的商品</div>
              <svg aria-hidden="true" class="navbar_svg" width="16" height="16">
                <use xlink:href="#icon-summary_question" />
              </svg>
            </el-tooltip>
            <el-checkbox v-model="usable_stock" @change="(val)=>{checkboxChange(val,'usable_stock')}">使用库存</el-checkbox>
            <el-tooltip class="item" effect="dark" placement="top">
              <div slot="content">
                注释：采购量=预定量-(库存-使用库存+在途库存)
              </div>
              <svg aria-hidden="true" class="navbar_svg" width="16" height="16">
                <use xlink:href="#icon-summary_question" />
              </svg>
            </el-tooltip>
            <el-checkbox v-model="calculate_losses" @change="(val)=>{checkboxChange(val,'calculate_losses')}">计算损耗</el-checkbox>
            <el-tooltip class="item" effect="dark" placement="top">
              <div slot="content">注释：预定量=预定量+（预定量*损耗率）</div>
              <svg aria-hidden="true" class="navbar_svg" width="16" height="16">
                <use xlink:href="#icon-summary_question" />
              </svg>
            </el-tooltip>
            <el-checkbox v-model="auto_merge_purchase" @change="(val)=>{checkboxChange(val,'auto_merge_purchase')}">自动合并</el-checkbox>
            <el-tooltip class="item" effect="dark" placement="top">
              <div slot="content">
                注释：存在相同采购日期、采购方式、采购人员、采购类型、仓库，且状态为待采购的采购单
              </div>
              <svg aria-hidden="true" class="navbar_svg" width="16" height="16">
                <use xlink:href="#icon-summary_question" />
              </svg>
            </el-tooltip>
        </div>
      </div>
      <div class="main_table" style="min-height: 570px">
        <el-table
          ref="multipleTable"
          v-loading="listLoading"
          :data="list.list"
          element-loading-text="加载中"
          fit
          border
          highlight-current-row
          :row-class-name="getRowClass"
          @select="onTableSelect"
          @expand-change="expandChange"
        >
          <el-table-column type="expand" class-name="main_hei">
            <template slot-scope="props">
              <el-table
                :ref="'expandchild' + props.$index"
                :data="props.row.order_list"
                class="mainex_ta"
                fit
                :row-class-name="getRowClass"
                :highlight-current-row="false"
                @select="
                  (rows, row) => {
                    expandSelect(rows, row, props.$index);
                  }
                "
              >
                <el-table-column type="selection" width="95" align="right" />
                <el-table-column label="订单号" prop="order_sn" width="200" />
                <el-table-column label="商户名称" width="100" prop="nickname" />
                <el-table-column label="采购方式" prop="name" width="320" class-name="main_hei">
                  <template slot-scope="scope">
                    <div class="box">
                      <el-select
                        v-model.trim="scope.row.type"
                        placeholder="采购方式"
                        class="wid120"
                      >
                        <el-option
                          v-for="(type_list, index) in list.type_list"
                          :key="index"
                          :label="type_list"
                          :value="parseInt(index)"
                        ></el-option>
                      </el-select>
                      <el-select
                        v-model.trim="scope.row.buyer_id"
                        placeholder="采购员"
                        class="wid160 marginLeft10"
                        v-if="scope.row.type==1"
                      >
                        <el-option
                          v-for="(buyer, index) in list.buyer"
                          :key="index"
                          :label="buyer"
                          :value="parseInt(index)"
                        ></el-option>
                      </el-select>
                      <el-select
                        v-model.trim="scope.row.supplier_id"
                        placeholder="供应商"
                        class="wid160 marginLeft10"
                        v-if="scope.row.type>1"
                      >
                        <el-option
                          v-for="(supplier, index) in list.supplier"
                          :key="index"
                          :label="supplier"
                          :value="parseInt(index)"
                        ></el-option>
                      </el-select>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column label="预定量" prop="order_num" />
                <el-table-column label="损耗率" prop="ullage" v-if="usable_stock"/>
                <el-table-column label="预定小计" width="100" prop="order_money" v-if="usable_stock"/>
                <el-table-column label="使用库存量" width="100" prop="use_inventory" v-if="calculate_losses"/>
                <el-table-column label="采购量" prop="purchase_num" />
              </el-table>
            </template>
          </el-table-column>

          <el-table-column type="selection" />
          <el-table-column
            label="商品名称"
            prop="name"
            width="180"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            label="单位"
            prop="unit"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            label="预定总量"
            prop="order_num"
            width="120"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            label="损耗率"
            prop="ullage"
            :show-overflow-tooltip="true"
            v-if="usable_stock"
          />
          <el-table-column
            label="预定合计"
            prop="order_money"
            width="120"
            v-if="usable_stock"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            label="库存量"
            prop="inventory"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            label="使用库存量"
            prop="use_inventory"
            width="120"
            v-if="calculate_losses"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            label="在途库存量"
            prop="in_pass_num"
            width="120"
            v-if="calculate_losses"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            label="采购量"
            prop="purchase_num"
            :show-overflow-tooltip="true"
          />
        </el-table>
      </div>
    </div>
  </div>
</template>

<script>
import { orderList_plan, purchase_addPlan, orderList_planGoods } from "@/api/purchasing/purchasingPlanned";
import { apiUrl, objKeySort, Md5 } from "@/utils/public";
import { recursion, category, parseTime } from "@/utils/index";
import { setting_company } from "@/api/currency";

export default {
  data() {
    return {
      // 搜索
      form: {
        name: "",
        pid: "",
        category_id: [],
        send_time: parseTime(new Date(),'{y}-{m}-{d}'),
        send_time_id: null,
        group_id: null,
      },
      low_stocks: false,
      usable_stock: false,
      calculate_losses: false,
      auto_merge_purchase: false,
      // 更多
      moredata: false,
      // 列表数据
      list: {
        list: [],
      },
      listLoading: false,
      // 分类
      options: [],
      defaultProps: {
        children: "selfNext",
        label: "title",
        value: "id",
        checkStrictly: true,
      },
    };
  },
  methods: {
    // 判断表格是否有子项，无子项不显示展开按钮
    getRowClass(row) {
      row.row.index = row.rowIndex;
      if (row.row.order_list) {
        if (row.row.order_list.length === 0) {
          return "row-expand-cover";
        }
      }
    },
    // 监听展开行
    expandChange(rows, row) {
      // console.log(rows)
      // console.log(row)
      if (rows.checked) {
        rows.order_list.forEach((chil) => {
          setTimeout(() => {
            if (chil.checked) {
              if (this.$refs["expandchild" + rows.index]) {
                this.$refs["expandchild" + rows.index].toggleRowSelection(
                  chil,
                  true
                );
              }
            }
          });
        });
      }
    },
    // 监听一级是否勾选
    onTableSelect(rows, row) {
      // console.log(rows, row)
      row.checked = !row.checked;
      if (row.checked) {
        row.order_list.forEach((m) => {
          if (this.$refs["expandchild" + row.index]) {
            this.$refs["expandchild" + row.index].toggleRowSelection(m, true);
          }
          m.checked = true;
        });
      } else {
        row.order_list.forEach((i) => {
          if (this.$refs["expandchild" + row.index]) {
            this.$refs["expandchild" + row.index].clearSelection();
          }
          i.checked = false;
        });
      }
    },
    // 监听二级是否勾选
    expandSelect(rows, row, index) {
      // console.log(rows)
      // console.log(row)
      // console.log(index)
      row.checked = !row.checked;
      let pchecked=false
      if (rows.length != 0) {
        this.list.list[index].checked = true;
        pchecked=true;
        this.$refs.multipleTable.toggleRowSelection(this.list.list[index], true);
      } else {
        this.list.list[index].checked = false;
        pchecked=false;
        this.$refs.multipleTable.toggleRowSelection(this.list.list[index], false);
      }
      let list=JSON.parse(JSON.stringify(this.list.list[index]))
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(
              Object.assign(apiUrl().name, this.list_form())
            ) + apiUrl().appsecret
          ),
        },
        apiUrl().name,
        this.list_form(),
        { ids:JSON.stringify(list.order_list.filter(e=> !e.checked).map(e=> e.order_list_id)),goods_id:list.goods_id,goods_spu_id:list.goods_spu_id,order_list_ids: JSON.stringify(list.order_list.map(e=> e.order_list_id)) }
      );
      orderList_planGoods(data).then((res) => {
        if (res.errcode == 0) {
          console.log(res.data)
          this.list.list[index].order_money=res.data.data.order_money
          this.list.list[index].order_num=res.data.data.order_num
          this.list.list[index].purchase_num=res.data.data.purchase_num
          this.list.list[index].ullage=res.data.data.ullage
          this.list.list[index].use_inventory=res.data.data.use_inventory
          res.data.data.order_list.map((e,ind)=>{
            this.list.list[index].order_list[ind].purchase_num=e.purchase_num
            this.list.list[index].order_list[ind].use_inventory=e.use_inventory
          })
        } else {
          this.$message.error(res.errmsg);
        }
      });
    },
    // 生成采购单
    generateClick(){
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(
              Object.assign(apiUrl().name)
            ) + apiUrl().appsecret
          ),
        },
        apiUrl().name,
        { list: this.list_data(),send_time:this.form.send_time }
      );
      if (JSON.parse(this.list_data()).length != 0) {
        purchase_addPlan(data).then((res) => {
          if (res.errcode == 0) {
            this.$message({
              message: "生成采购单成功",
              type: "success",
            });
            this.orderList_plan();
          } else {
            this.$message.error(res.errmsg);
          }
        });
      } else {
        this.$message.error("请勾选商品");
      }
    },
    // 搜索勾选
    checkboxChange(val,type) {
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(
              Object.assign(apiUrl().name, {[type]:val ? 1 : 0})
            ) + apiUrl().appsecret
          ),
        },
        apiUrl().name,
        {[type]:val ? 1 : 0}
      );
      setting_company(data).then((res) => {
        if (res.errcode == 0) {
          this.orderList_plan();
        } else {
          this.$message.error(res.errmsg);
        }
      });
    },
    // 导出明细
    exportb() {
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name,this.list_form())) +
              apiUrl().appsecret
          ),
        },
        apiUrl().name,
        this.list_form()
      );
      orderList_planw(data).then((res) => {
        if (res.errcode == 0) {
          this.$message({
            message: "导出成功",
            type: "success",
          });
        } else {
          this.$message.error(res.errmsg);
        }
      });
    },
    // 搜索
    getArticleList() {
      this.orderList_plan();
    },
    // 更多
    more() {
      this.moredata = !this.moredata;
    },
    // 列表
    orderList_plan() {
      this.listLoading = true;
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(
              Object.assign(apiUrl().name, this.list_form(), this.current)
            ) + apiUrl().appsecret
          ),
        },
        apiUrl().name,
        this.list_form(),
        this.current
      );
      orderList_plan(data).then((res) => {
        this.listLoading = false;
        if (res.errcode == 0) {
          this.options = recursion(res.data.categoryList, true);
          res.data.list.map((e,index) => {
            e.checked = true;
            e.order_list.map((p)=>{
              p.buyer_id=p.buyer_id==0?null:p.buyer_id
              p.supplier_id=p.supplier_id==0?null:p.supplier_id
              p.checked = true;
            })
            this.$nextTick(()=>{
              if(this.$refs["multipleTable"]){
                this.$refs["multipleTable"].toggleRowSelection(e, true);
              }
            })
          });
          this.low_stocks = res.data.low_stocks==1?true:false;
          this.usable_stock = res.data.usable_stock==1?true:false;
          this.calculate_losses = res.data.calculate_losses==1?true:false;
          this.auto_merge_purchase = res.data.auto_merge_purchase==1?true:false;
          this.list = res.data;
        } else {
          this.$message.error(res.errmsg);
        }
      });
    },
    list_form() {
      let form = JSON.parse(JSON.stringify(this.form));
      form.pid = form.category_id[0] ? form.category_id[0] : "";
      form.category_id = category(form.category_id);

      return form;
    },
    list_data(){
      let arry=[];
      let list = JSON.parse(JSON.stringify(this.list.list));
      list.map((e,index)=>{
        if(e.checked){
          e.order_list.map(p=>{
            if(p.checked){
              arry.push({goods_id:e.goods_id,goods_spu_id:e.goods_spu_id,unit:e.unit,goods_name:e.goods_name,spu_name:e.spu_name,order_list_id:p.order_list_id,use_inventory:p.use_inventory,type:p.type,purchase_num:p.purchase_num,order_num:p.order_num,ullage:p.ullage,buyer_id:p.buyer_id==null?0:p.buyer_id,supplier_id:p.supplier_id==null?0:p.supplier_id})
            }
          })
        }
      })

      return JSON.stringify(arry)
    },
  },
  created() {
    // 列表
    this.orderList_plan();
  },
};
</script>
<style lang="scss" scoped>
.mainor_form form {
  width: calc(100% - 280px);
}
.main_num {
  .main_num_l {
    width: calc(100% - 560px);
  }
}
</style>
